<!--
 * @Author: your name
 * @Date: 2021-06-03 19:40:42
 * @LastEditTime: 2021-06-04 10:16:46
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \画布\基础画布.html
-->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        canvas {
            border: 1px solid red;
            display: block;
        }
    </style>
</head>

<body>
    <!-- 不设置宽高。存在默认宽高 -->
    <canvas width="600" height="600">设置线段</canvas>
    <button id="btn">清除</button>
    <input type="color" id="seleot">
</body>
<script>
    var myCanvas = document.querySelector("canvas")
    var btn = document.querySelector("#btn")
    var colorInp = document.querySelector("#seleot")
    var ctx = myCanvas.getContext("2d")
    ctx.strokeStyle = "red"
    colorInp.onchange = function () {
        ctx.strokeStyle = colorInp.value;
    }
    // 鼠标按下时事件
    myCanvas.onmousedown = function (e) {
        // 鼠标按下时距离浏览器的距离 
        var x = e.clientX - myCanvas.offsetLeft;
        var y = e.clientY - myCanvas.offsetTop;
        ctx.beginPath()
        ctx.moveTo(x, y)
        myCanvas.onmousemove = function (e) {
            var mx = e.clientX - myCanvas.offsetLeft;
            var my = e.clientY - myCanvas.offsetTop;
            ctx.lineTo(mx, my)
            ctx.stroke()

        }
        myCanvas.onmouseup = function (e) {
            //不做任何操作//dom0级事件解除事件绑定
            myCanvas.onmousemove = null;
            myCanvas.onmouseup = null;
        }
    }
    btn.onclick = function () {
        myCanvas.Width = 600;
        myCanvas.height = 600;
        ctx.clearRect(0, 0, 600, 600)
    }

</script>

</html>